#!/bin/bash
#

USER="admin"
PASS="XXXXXXXXXXXXXXXXXX"
HURL="https://{{ HARBOR_DOMAIN }}"
MTAG=$2
CONTAIN=$3

function usage() {
cat << HELP

docker-tag  --  list all tags for a Docker image on a remote registry

EXAMPLE:
    - list all tags for ubuntu:
       docker-tag tags ubuntu

    - list all php tags containing apache:
       docker-tag tags php apache

    - list all images of harbor:
       docker-tag get_images

    - list all tags for harbor redis:
       docker-tag get_tags redis/redis

HELP
}

if [ $# -lt 1 ]; then
	usage
	exit 2
fi

function tags() {
    TAGS=$(curl -ksL https://registry.hub.docker.com/v1/repositories/${MTAG}/tags | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | tr '}' '\n'  | awk -F: '{print $3}')
    if [ "${CONTAIN}" != "" ]; then
        echo -e $(echo "${TAGS}" | grep "${CONTAIN}") | tr ' ' '\n'
    else
        echo "${TAGS}"
    fi
}

function get_images() {
    RTOKEN=$(curl -k -s  -u ${USER}:${PASS} ${HURL}/service/token?account=${USER}\&service=harbor-registry\&scope=registry:catalog:* | grep "token" | awk -F '"' '{print $4}')
    RLIST=$(curl -k -s -H "authorization: bearer ${RTOKEN} " ${HURL}/v2/_catalog | awk -F '[' '{print $2}'|awk -F ']' '{print $1}' | sed 's/"//g')
    echo ${RLIST} | tr ',' '\n'
}

function get_tags() {
    TTOKEN=$(curl -iksL -X GET -u ${USER}:${PASS} ${HURL}/service/token?account=${USER}\&service=harbor-registry\&scope=repository:${MTAG}:pull | grep "token" | awk -F '"' '{print $4}')
    TLIST=$(curl -ksL -X GET -H "Content-Type: application/json" -H "Authorization: Bearer ${TTOKEN}" ${HURL}/v2/${MTAG}/tags/list| awk -F '[' '{print $2}' | awk -F ']' '{print $1}' | sed 's/"//g')
    echo ${TLIST} | tr ',' '\n'
}

case $1 in
    get_images)
        get_images
        ;;
    get_tags)
        get_tags
        ;;
    tags)
        tags
        ;;
    *)
        usage
        ;;
esac
